#ifndef __M_FMT_H__
#define __M_FMT_H__

// ⽇志输出格式化类
// 通过基类派生类来进行获取日志信息并格式化字符串
#include <ctime>
#include <vector>
#include <cassert>
#include <sstream>
#include "level.hpp"
#include "message.hpp"

namespace gjclog
{
    // 日志格式化子项类
    // 基类，抽象类
    class FormarItem
    {
    public:
        using ptr = std::shared_ptr<FormarItem>;
        virtual void format(std::ostream &out, const LogMsg &msg) = 0;
    };

    // 从LogMsg中获取有效载荷的派生类
    class MsgFormarItem : public FormarItem
    {
    public:
        void format(std::ostream &out, const LogMsg &msg) override
        {
            out << msg._payload;
        }
    };
    // 从LogMsg中获取日志等级的派生类
    class LevelFormarItem : public FormarItem
    {
    public:
        void format(std::ostream &out, const LogMsg &msg) override
        {
            out << LogLevel::toString(msg._level);
        }
    };
    // 从LogMsg中获取时间的派生类——将时间戳转换为字符串形式再添加
    class TimeFormarItem : public FormarItem
    {
    public:
        TimeFormarItem(const std::string &fmt = "%H:%M:%S")
            : _time_fmt(fmt)
        {
        }

        void format(std::ostream &out, const LogMsg &msg) override
        {
            // 1. 将时间戳提取转化为结构化时间
            struct tm t;
            localtime_r(&msg._ctime, &t);
            // 2. 将结构化时间转化为字符串时间
            char tmp[32] = {0};
            strftime(tmp, 31, _time_fmt.c_str(), &t);
            out << tmp;
        }

    private:
        std::string _time_fmt;  // %H:%M:%S
    };

    // 从LogMsg中获取文件名的派生类
    class FileFormarItem : public FormarItem
    {
    public:
        void format(std::ostream &out, const LogMsg &msg) override
        {
            out << msg._file;
        }
    };

    // 从LogMsg中获取行号的派生类
    class LineFormarItem : public FormarItem
    {
    public:
        void format(std::ostream &out, const LogMsg &msg) override
        {
            out << msg._line;
        }
    };

    // 从LogMsg中获取线程ID的派生类
    class ThreadFormarItem : public FormarItem
    {
    public:
        void format(std::ostream &out, const LogMsg &msg) override
        {
            out << msg._tid;
        }
    };

    // 从LogMsg中获取日志器名称的派生类
    class LoggerFormarItem : public FormarItem
    {
    public:
        void format(std::ostream &out, const LogMsg &msg) override
        {
            out << msg._logger;
        }
    };

    // 制表符派生类
    class TabFormarItem : public FormarItem
    {
    public:
        void format(std::ostream &out, const LogMsg &msg) override
        {
            out << "\t";
        }
    };

    // 换行派生类
    class NLineFormarItem : public FormarItem
    {
    public:
        void format(std::ostream &out, const LogMsg &msg) override
        {
            out << "\n";
        }
    };

    // 其他字符/内容派生类：[]...
    class OtherFormarItem : public FormarItem
    {
    public:
        OtherFormarItem(const std::string &str)
            : _str(str)
        {
        }

        void format(std::ostream &out, const LogMsg &msg) override
        {
            out << _str;
        }

    private:
        std::string _str;
    };

    // %d⽇期：子项%H:%M:%S
    // %T缩进
    // %t线程id
    // %p⽇志等级
    // %c⽇志器名称
    // %f⽂件名
    // %l⾏号
    // %m⽇志消息
    // %n换⾏
    class Formatter
    {
    public:
        using ptr = std::shared_ptr<Formatter>;
    public:
        Formatter(const std::string &pattern = "[%d{%H:%M:%S}][%t][%c][%f:%l][%p]%T%m%n")
            : _pattern(pattern)
        {
            assert(parsePattern());
        }
        // 对message进行格式化
        void format(std::ostream &out, const LogMsg &msg)
        {
            for (auto &item : _items)
            {
                item->format(out, msg);
            }
        }
        std::string format(const LogMsg &msg)
        {
            std::stringstream ss;
            format(ss, msg);
            return ss.str();
        }

    private:
        // 对格式化规则字符串进行解析——获得格式化子项数组中的内容
        bool parsePattern()
        {
            // 对格式化规则字符串进行解析
            std::vector<std::pair<std::string, std::string>> fmt_order;
            size_t pos = 0;
            std::string key, val;
            while (pos < _pattern.size())
            {
                // 1.处理原始字符串，判断是否为%，不是就是原始字符
                if (_pattern[pos] != '%')
                {
                    val.push_back(_pattern[pos++]);
                    continue;
                }

                // 2.如果pos位置是%，判断下一个是不是%
                if (pos + 1 < _pattern.size() && _pattern[pos + 1] == '%')
                {
                    val.push_back('%');
                    pos += 2;
                    continue;
                }
                // pos位置后面是格式化字符，表示原始字符串处理完毕；如果val为空则表示一开始就是格式化字符
                if (val.empty() == false)
                {
                    fmt_order.push_back(std::make_pair("", val));
                    val.clear();
                }

                // 3.pos的下一位是格式化字符，判断有没有子串{}
                pos += 1;
                if (pos == _pattern.size())
                {
                    std::cout << "%之后缺少对应的格式化字符！\n";
                    return false;
                }
                key = _pattern[pos];
                pos += 1;
                if (pos < _pattern.size() && _pattern[pos] == '{')
                {
                    // pos指向子串起始位置
                    pos += 1;
                    while (pos < _pattern.size() && _pattern[pos] != '}')
                    {
                        val.push_back(_pattern[pos++]);
                    }
                    // 没有遇到 } ，表示格式错误，返回false
                    if (pos == _pattern.size())
                    {
                        std::cout << "子规则{}匹配出错!\n";
                        return false;
                    }
                    pos += 1; // pos指向 } 的下一个位置，为下次解析做准备
                }
                fmt_order.push_back(std::make_pair(key, val));
                key.clear();
                val.clear();
            }

            // 根据解析得的数据初始化格式化子项数组成员
            for (auto &it : fmt_order)
            {
                _items.push_back(createItem(it.first, it.second));
            }
            return true;
        }

        // 根据不同的格式化字符创建不同的格式化对象：比如%d对应%H:%M:%S
        FormarItem::ptr createItem(const std::string &key, const std::string &val)
        {
            if (key == "d")
                return std::make_shared<TimeFormarItem>(val);
            if (key == "t")
                return std::make_shared<ThreadFormarItem>();
            if (key == "c")
                return std::make_shared<LoggerFormarItem>();
            if (key == "f")
                return std::make_shared<FileFormarItem>();
            if (key == "l")
                return std::make_shared<LineFormarItem>();
            if (key == "p")
                return std::make_shared<LevelFormarItem>();
            if (key == "T")
                return std::make_shared<TabFormarItem>();
            if (key == "m")
                return std::make_shared<MsgFormarItem>();
            if (key == "n")
                return std::make_shared<NLineFormarItem>();
            if (key == "")
            return std::make_shared<OtherFormarItem>(val);
            std::cout << "没有对应的格式化字符: %" << key << std::endl;
            abort();
            return FormarItem::ptr();
        }

    private:
        std::string _pattern;                // 格式化规则字符串
        std::vector<FormarItem::ptr> _items; // 格式化子项数组，按顺序遍历数组，从消息msg中取出数据进行format得到数据
    };
}

#endif